window.top.Historics = {
  extensionDir: function(){
  	return __LOCATION__.parent.parent;
  },
  preferences: null,
  onLoad: function() {
      /*
      try {
        /*
         *  Get a Foo component
         */
        var foo = this.getClassLoader();
        /*
         *  Initialize it. The trick is to get past its IDL interface
         *  and right into its Javascript implementation, so that we
         *  can pass it the LiveConnect "java" object, which it will
         *  then use to load its JARs. Note that XPCOM Javascript code
         *  is not given LiveConnect by default.
         
        if (!foo.wrappedJSObject.initialize(java, true)) {
            alert(foo.wrappedJSObject.error);
        }
    } catch (e) {
        alert(e);
    }
    */
  	window.top.Historics.preferences = Components.classes["@mozilla.org/preferences-service;1"]
                                .getService(Components.interfaces.nsIPrefService)
                                .getBranch("extensions.historics.");
    /* initialize the search index - pass in the function to be called on completion */
    window.top.Historics.SearchIndex.setup(window.top.Historics.updateHistoryResults);
    window.top.Historics.SearchIndex.addOnPageCachedListener(
    	function(){
    		window.setTimeout(window.top.Historics.updateHistoryResults, 1000);
    	}
    );
    /* get a handler to the browser */
    var appcontent = document.getElementById("appcontent");
    /* every time a new page is loaded */
    if(appcontent)
      appcontent.addEventListener("load", this.onPageLoad, true);
    
    window.top.Historics.cachePageTimers = new Array();
    window.top.Historics.doc = document;
    window.top.Historics.initialized = true;
  },
  onUnLoad: function() {
  	/* stop any pending page saving activities */
	  if(window.top.Historics.cachePageTimers){
	  	while(window.top.Historics.cachePageTimers.length>0)
	  		window.clearTimeout(window.top.Historics.cachePageTimers.pop());
	  }
    /* let the search index cleanup nicely */
    window.top.Historics.SearchIndex.teardown();
  },
  onPageLoad: function(aEvent){
  	/* get the a handler to the new document */
  	var doc = aEvent.originalTarget;
	if(!doc || !doc.location) return;
  	
  	
  	var pageFilterRE = "^http";
  	if(window.top.Historics.preferences.getBoolPref("indexsecure")) pageFilterRE += "[s]{0,1}";
  	pageFilterRE += "\\:";
  	/* make sure we don't index non http(s) pages, sub-frames, or pages the user has already left */
  	if(!window.top.Historics.isURIActive(doc.location.href) || !doc.location.href.match(new RegExp(pageFilterRE, "gi"))){
  		return;
  	}
  	
  	/* add this page to the cache */
  	window.top.Historics.cachePageTimers.push(
  		window.setTimeout(function(){window.top.Historics.SearchIndex.cache(doc);},
  			window.top.Historics.preferences.getIntPref("indexpagewait")));
  },
  updateHistoryResults: function(){
    var d = window.top.document.getElementById("sidebar").contentDocument;
    /* if the sidebar isn't open, no need to update */
  	if(window.top.document.getElementById("sidebar-box").hidden) return;
  	//window.alert("Going to update the list");
  	var query = d.getElementById("search-box").value;
  	var searchResultsBox = d.getElementById("searchResultsBox");
  	/* clear any old search results */
  	while(searchResultsBox.firstChild) searchResultsBox.removeChild(searchResultsBox.firstChild);
  	//window.alert("cleared the current items");
  	var pages = window.top.Historics.SearchIndex.search(query);
  	
  	for(var key in pages){
  		var box = d.createElement("vbox");
  		box.setAttribute("align", "center");
  		box.setAttribute("class", "searchResultsPage");
  	
  		var image = d.createElement("image");
  		image.setAttribute("src", "file://" + pages[key].thumbSrc);
  		image.setAttribute("tooltiptext", pages[key].title);
  		image.setAttribute("contextmenu", "hstPageContextMenu");
  		image.setAttribute("class", "pageThumbnailImage");
  		image.setAttribute("href", pages[key].url);
  		image.setAttribute("pageKey", key);
  		image.onmouseover = function(){
			window.top.Historics.Utils.addClassName(this, "over");
		}
  		image.onmouseout = function(){
			window.top.Historics.Utils.removeClassName(this, "over");
		}
		image.onclick = function(){
			gBrowser.selectedBrowser.contentDocument.location = this.getAttribute("href");
		}
  		box.appendChild(image);
  		
  		var label = d.createElement("label");
  		label.setAttribute("value", window.top.Historics.Utils.truncate(pages[key].title, 45));
  		box.appendChild(label);
  		
  		searchResultsBox.appendChild(box);
  	}
  },
  onMenuItemCommand: function() {
    window.open("chrome://historics/content/historics.xul", "", "chrome");
  },
  onSidebarToggle: function(){
  	//window.top.document.getElementById("sidebar-box").width = 400;
  	toggleSidebar('viewEmptySidebar');
  	window.setTimeout(window.top.Historics.updateHistoryResults, 100);
  	//window.alert(window.top.document.getElementById("sidebar-box").hidden);
  },
  /* make sure the given doc is active in that one of the open browsers 
  is displaying it */
  isDocActive: function(doc){
  	for(var i=0; i<gBrowser.browsers.length; i++){
  		if(gBrowser.getBrowserAtIndex(i).contentDocument==doc) return true;
  	}
  	return false;
  },
  /* make sure the given uri is active in that one of the open browsers 
  is displaying it */
  isURIActive: function(uri){
  	for(var i=0; i<gBrowser.browsers.length; i++){
  		if(gBrowser.getBrowserAtIndex(i).currentURI.spec==uri) return true;
  	}
  	return false;
  },
  buildContextMenu: function(event){
  	window.alert(event.currentTarget.tagName);
  },
  deleteCurrentPage: function(){
  	window.alert("Going to delete page");
  },
  showHistoryBrowser: function(){
  	var historyBrowser = window.top.Historics.getClassLoader().wrappedJSObject.
					getHistoryBrowser();
	alert(historyBrowser.getPath());
	historyBrowser.setVisible(true);
  }
};
window.top.Historics.getClassLoader = function() {
    return Components.classes["@gethistorics.com/historics;1"]
        .getService(Components.interfaces.nsIHistorics);
}

window.addEventListener("load", function(e) { window.top.Historics.onLoad(e); }, false);
window.addEventListener("unload", function(e) { window.top.Historics.onUnLoad(e); }, false); 